/*
*Copyright 2021-2023 NERCIS
*
*Licensed under the Apache License, Version 2.0 (the "License");
*you may not use this file except in compliance with the License.
*You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*Unless required by applicable law or agreed to in writing, software
*distributed under the License is distributed on an "AS IS" BASIS,
*WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*See the License for the specific language governing permissions and
*limitations under the License.
*/

package cn.ac.nercis.pes.community.controller.evaluation;

import cn.ac.nercis.pes.common.constant.project.SystemState;
import cn.ac.nercis.pes.community.component.controls.CustomScrollPane;
import cn.ac.nercis.pes.community.component.controls.MenuBlockControl;
import cn.ac.nercis.pes.community.controller.base.BaseWindow;
import cn.ac.nercis.pes.community.controller.dialog.ScoreInfoController;
import cn.ac.nercis.pes.community.controller.evaluation.analyze.AnalyzeController;
import cn.ac.nercis.pes.community.controller.evaluation.document.GenerateDocController;
import cn.ac.nercis.pes.community.controller.evaluation.onsite.EvalController;
import cn.ac.nercis.pes.community.controller.evaluation.photo.PhotoManageController;
import cn.ac.nercis.pes.community.controller.evaluation.planning.PlanningController;
import cn.ac.nercis.pes.community.controller.evaluation.prepare.PrepareController;
import cn.ac.nercis.pes.community.controller.evaluation.proof.ProofController;
import cn.ac.nercis.pes.community.controller.project.TaskManageController;
import cn.ac.nercis.pes.community.support.AbstractFxmlView;
import cn.ac.nercis.pes.community.support.controls.JFXPopup;
import cn.ac.nercis.pes.community.utils.*;
import cn.ac.nercis.pes.community.views.dialog.ScoreInfoView;
import cn.ac.nercis.pes.community.views.evaluation.analyze.AnalyzeView;
import cn.ac.nercis.pes.community.views.evaluation.document.GenerateDocView;
import cn.ac.nercis.pes.community.views.evaluation.onsite.EvalView;
import cn.ac.nercis.pes.community.views.evaluation.photo.PhotoManageView;
import cn.ac.nercis.pes.community.views.evaluation.planning.PlanningView;
import cn.ac.nercis.pes.community.views.evaluation.prepare.PrepareView;
import cn.ac.nercis.pes.community.views.evaluation.proof.ProofView;
import cn.ac.nercis.pes.service.project.SystemService;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.Separator;
import javafx.scene.control.Tooltip;
import javafx.scene.input.MouseButton;
import javafx.scene.layout.*;
import javafx.stage.Stage;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.net.URL;
import java.util.Objects;
import java.util.ResourceBundle;

/**
 * 测评管理控制器
 * @author zpy
 * @version 1.0.0
 */
@Slf4j
public class EvaluationController extends BaseWindow implements Initializable {

    @FXML
    private StackPane page;
    @FXML
    private BorderPane bodyPane;
    @FXML
    private HBox titleBar;
    @FXML
    private Label titleLbl;

    @FXML
    private Button btnScore;
    @FXML
    private Button btnMenuList;
    @FXML
    private Separator mainMenuSeparator;
    @FXML
    private HBox mainMenuBox;
    @FXML
    private Button btnFull;
    @FXML
    private Button btnMin;
    @FXML
    private Button btnClose;
    @FXML
    private Button btnMax;

    @FXML
    private CustomScrollPane menuPage;
    @FXML
    private FlowPane evalMenus;
    @FXML
    private FlowPane fixMenus;
    @FXML
    private VBox evalPage;
    @FXML
    private StackPane systemEvaluationPopupBox;
    private String currentSystemId;
    private Stage currentStage;
    private JFXPopup scorePopup;

    private JFXPopup systemEvaluationPopup;

    private final SystemService systemService;

    public EvaluationController() {
        systemService = SpringUtils.getBean(SystemService.class);
    }

    /**
     * 初始化
     */
    @Override
    public void initialize(URL location, ResourceBundle resources) {
        this.initControl();
    }

    public void initData(@NonNull String systemId,String defaultModel){
        this.currentSystemId = systemId;
        this.evalPage.setVisible(false);
        this.menuPage.setVisible(true);
        var currentSystem = Objects.requireNonNull(AppStore.getCurrentSystem(systemId));
        this.titleLbl.setText(ControlUtils.getEvaluationWindowTitle(currentSystem.getSystemName()));
        this.currentStage = currentSystem.getEvaluationStage();
        this.currentStage.fullScreenProperty().addListener(isFullScreen->{
            if(!this.currentStage.isFullScreen()){
                this.mainMenuSeparator.setVisible(true);
                this.mainMenuBox.setVisible(true);
                if(!this.maximized){
                    this.maximizedSettingApply(false);
                }
            }
        });
        titleBar.setOnMouseDragged((event)->{
            if(!this.maximized && !currentStage.isFullScreen()){
                this.onMouseDragged(event,this.currentStage);
            }
        });
        this.initScoreInfo();
        ResizeWindowUtils.appendResizeFunc(currentStage,this.bodyPane);
        titleBar.setOnMousePressed(this::onMousePressed);
        //非Window系统移除全屏功能
        if(!SystemUtils.isWindowOs()){
            btnFull.setVisible(false);
        }
        if(StringUtils.isNotBlank(defaultModel)){
            onMenuItemClick(defaultModel);
        }
    }

    public void gotoEvaluationModel(String model){
        if(StringUtils.isNotBlank(model)){
            onMenuItemClick(model);
        }
    }

    @FXML
    public void onMenuListClick(){
        if (this.evalPage.isVisible()) {
            systemEvaluationPopup.show(btnMenuList, JFXPopup.PopupVPosition.TOP, JFXPopup.PopupHPosition.LEFT,
                    10, btnScore.getHeight() + 14);
        }
    }

    @FXML
    public void popScoreInfo(){
        var scoreInfoView = AppStore.getEvaluationView(this.currentSystemId, ScoreInfoView.class);
        scorePopup.show(btnScore,JFXPopup.PopupVPosition.TOP,JFXPopup.PopupHPosition.LEFT,
                -100,btnScore.getHeight()+14);
        if(scoreInfoView.getController() instanceof ScoreInfoController controller){
            controller.refreshScore();
        }
    }

    private void initScoreInfo(){
        var scoreInfoView = AppStore.getEvaluationView(this.currentSystemId, ScoreInfoView.class);
        scorePopup = new JFXPopup((Region) Objects.requireNonNull(scoreInfoView).load());
        if(scoreInfoView.getController() instanceof ScoreInfoController controller){
            controller.initializeData(this.currentSystemId,this.btnScore);
        }
    }

    private void initControl(){
        this.btnFull.setGraphic(IconUtils.getGlyph("win-full","main-title-bar-close-icon"));
        this.btnClose.setGraphic(IconUtils.getGlyph("win-close","main-title-bar-close-icon"));
        this.btnMin.setGraphic(IconUtils.getGlyph("win-min","main-title-bar-min-icon"));
        this.btnMax.setGraphic(IconUtils.getGlyph("win-max", "main-title-bar-max-icon"));
        this.btnMenuList.setGraphic(IconUtils.getGlyph("menu-list-icon", "main-title-bar-list-icon"));

        this.mainMenuSeparator.managedProperty().bind(this.mainMenuSeparator.visibleProperty());
        this.mainMenuBox.managedProperty().bind(this.mainMenuBox.visibleProperty());
        this.btnFull.managedProperty().bind(this.btnFull.visibleProperty());
        this.evalPage.managedProperty().bind(this.evalPage.visibleProperty());
        this.menuPage.managedProperty().bind(this.menuPage.visibleProperty());
        this.titleBar.setOnMouseClicked((mouseEvent)->{
            if(mouseEvent.getButton().equals(MouseButton.PRIMARY) && mouseEvent.getClickCount() == DOUBLE_CLICK){
                onMaxWindow();
            }
        });
        this.initMenus();
        systemEvaluationPopup = new JFXPopup(systemEvaluationPopupBox);
    }

    private void initMenus(){
        this.evalMenus.getChildren().clear();
        this.evalMenus.getChildren().add(new MenuBlockControl("images/menu/menu-block1.jpg","测评准备",this::onMenuItemClick));
        this.evalMenus.getChildren().add(new MenuBlockControl("images/menu/menu-block2.jpg","方案编制",this::onMenuItemClick));
        this.evalMenus.getChildren().add(new MenuBlockControl("images/menu/menu-block3.jpg","现场测评",this::onMenuItemClick));
        this.evalMenus.getChildren().add(new MenuBlockControl("images/menu/menu-block4.jpg","分析与报告编制",this::onMenuItemClick));

        this.fixMenus.getChildren().clear();
        this.fixMenus.getChildren().add(new MenuBlockControl("images/menu/menu-block7.jpg","密评证明记录",this::onMenuItemClick));
        this.fixMenus.getChildren().add(new MenuBlockControl("images/menu/menu-block5.jpg","证据文件管理",this::onMenuItemClick));
        this.fixMenus.getChildren().add(new MenuBlockControl("images/menu/menu-block6.jpg","生成测评文档",this::onMenuItemClick));
    }

    private void onMenuItemClick(String menuText){
        switch (menuText) {
            case "测评准备" -> {
                systemService.setSystemState(currentSystemId, SystemState.PREPARE);
                SpringUtils.getBean(TaskManageController.class).reloadSystemList();
                var prepareView = AppStore.getEvaluationView(this.currentSystemId, PrepareView.class);
                loadContent(Objects.requireNonNull(prepareView));
                if (prepareView.getController() instanceof PrepareController controller) {
                    controller.initializeData(this.currentSystemId);
                }
            }
            case "方案编制" -> {
                systemService.setSystemState(currentSystemId, SystemState.PLANNING);
                SpringUtils.getBean(TaskManageController.class).reloadSystemList();
                var planningView = AppStore.getEvaluationView(this.currentSystemId, PlanningView.class);
                loadContent(Objects.requireNonNull(planningView));
                if (planningView.getController() instanceof PlanningController controller) {
                    controller.initializeData(this.currentSystemId);
                }
            }
            case "现场测评" -> {
                systemService.setSystemState(currentSystemId, SystemState.EVALUATION);
                SpringUtils.getBean(TaskManageController.class).reloadSystemList();
                var evaView = AppStore.getEvaluationView(this.currentSystemId, EvalView.class);
                loadContent(Objects.requireNonNull(evaView));
                if (evaView.getController() instanceof EvalController controller) {
                    controller.initializeData(this.currentSystemId);
                }
            }
            case "证据文件管理" -> {
                var manageView = AppStore.getEvaluationView(this.currentSystemId, PhotoManageView.class);
                loadContent(Objects.requireNonNull(manageView));
                if (manageView.getController() instanceof PhotoManageController controller) {
                    controller.initializeData(this.currentSystemId);
                }
            }
            case "生成测评文档" -> {
                var docView = AppStore.getEvaluationView(this.currentSystemId, GenerateDocView.class);
                loadContent(Objects.requireNonNull(docView));
                if (docView.getController() instanceof GenerateDocController controller) {
                    controller.initializeData(this.currentSystemId);
                }
            }
            case "分析与报告编制" -> {
                systemService.setSystemState(currentSystemId, SystemState.REPORT);
                SpringUtils.getBean(TaskManageController.class).reloadSystemList();
                var analyzeView = AppStore.getEvaluationView(this.currentSystemId, AnalyzeView.class);
                loadContent(Objects.requireNonNull(analyzeView));
                if (analyzeView.getController() instanceof AnalyzeController controller) {
                    controller.initializeData(this.currentSystemId);
                }
            }
            case "密评证明记录" -> {
                systemService.setSystemState(currentSystemId, SystemState.PROOF);
                SpringUtils.getBean(TaskManageController.class).reloadSystemList();
                var proofView = AppStore.getEvaluationView(this.currentSystemId, ProofView.class);
                loadContent(Objects.requireNonNull(proofView));
                if (proofView.getController() instanceof ProofController controller) {
                    controller.initializeData(this.currentSystemId);
                }
            }
            default -> {
            }
        }
        var currentSystem = Objects.requireNonNull(AppStore.getCurrentSystem(this.currentSystemId));
        this.titleLbl.setText(ControlUtils.getEvaluationWindowTitle(currentSystem.getSystemName(),menuText));

        this.currentStage.setTitle(ControlUtils.getEvaluationWindowTitle(currentSystem.getSystemName(),menuText));
    }

    private void loadContent(AbstractFxmlView view){
        var content = view.load();
        this.evalPage.getChildren().clear();
        this.evalPage.getChildren().add(content);
        this.menuPage.setVisible(false);
        this.evalPage.setVisible(true);
    }

    @FXML
    public void onFullWindow(){
        this.currentStage.setFullScreen(true);
        this.maximizedSettingApply(true);
        this.mainMenuSeparator.setVisible(false);
        this.mainMenuBox.setVisible(false);
    }

    @FXML
    public void onMinWindow(){
        this.currentStage.setIconified(true);
    }

    @FXML
    public void onMaxWindow(){
        this.windowMax(this.currentStage);
        this.maximizedSettingApply(this.maximized);
        this.btnFull.setVisible(!this.maximized);
    }

    private void maximizedSettingApply(Boolean isMax){
        if(isMax){
            //最大化
            this.btnMax.setGraphic(IconUtils.getGlyph("win-res", "main-title-bar-res-icon"));
            this.btnMax.setTooltip(new Tooltip("还原"));
            this.page.getStyleClass().remove("page");
            this.page.getStyleClass().add("max-page");

        }else{
            //还原
            this.btnMax.setGraphic(IconUtils.getGlyph("win-max", "main-title-bar-max-icon"));
            this.btnMax.setTooltip(new Tooltip("最大化"));
            this.page.getStyleClass().remove("max-page");
            this.page.getStyleClass().add("page");
        }
    }

    @FXML
    public void onClose() {
        this.currentStage.close();
        AppStore.disposeSystem(this.currentSystemId);
        System.gc();
    }

    public void onPrepare() {
        this.onMenuItemClick("测评准备");
        this.systemEvaluationPopup.hide();
    }

    public void onPlanning() {
        this.onMenuItemClick("方案编制");
        this.systemEvaluationPopup.hide();
    }

    public void onEval() {
        this.onMenuItemClick("现场测评");
        this.systemEvaluationPopup.hide();
    }

    public void onAnalyze() {
        this.onMenuItemClick("分析与报告编制");
        this.systemEvaluationPopup.hide();
    }

    public void onProof() {
        this.onMenuItemClick("密评证明记录");
        this.systemEvaluationPopup.hide();
    }

    public void onPhotoManage() {
        this.onMenuItemClick("证据文件管理");
        this.systemEvaluationPopup.hide();
    }

    public void onGenerateDoc() {
        this.onMenuItemClick("生成测评文档");
        this.systemEvaluationPopup.hide();
    }

}